package cn.javadog.smartbreeding.record.config;

import javax.annotation.Resource;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author 余勇
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Resource
	private TokenExceptionHandler tokenExceptionHandler;
	@Resource
	private AccessDeniedHandler accessDeniedHandler;
	@Resource
	private JwtTokenFilter jwtTokenFilter;

	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		httpSecurity
			// 因为我们的token是无状态的，不需要跨站保护
			.csrf().disable()
			// 添加异常处理，以及访问禁止（无权限）处理
			.exceptionHandling().authenticationEntryPoint(tokenExceptionHandler).accessDeniedHandler(accessDeniedHandler).and()
			// 我们不再需要session了
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
			//定义拦截页面，所有api全部需要认证
			.authorizeRequests()
			.anyRequest().authenticated();

		//最后，我们定义 filter，用来替换原来的UsernamePasswordAuthenticationFilter
		httpSecurity.addFilterAt(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		// 让我们获取 token的api不走spring security的过滤器，大道开放
		web.ignoring()
			.antMatchers("/swagger-ui.html")
			.antMatchers("/webjars/**")
			.antMatchers("/v2/**")
			.antMatchers("/doc.html")
			.antMatchers("/swagger-resources/**")
			.antMatchers("/record/**")
			.antMatchers("/temperature/**")
			.antMatchers("/temperature/records/**")
			.antMatchers(HttpMethod.GET, "/auth/login");
	}
}
